﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace MaxAlarm.Core.Cryptography
{
    public static class CryptorProviderHelper
    {
        const string Key = "MaxAlarmPassword";

        public static string Encrypt(string toEncrypt, bool useHasing = true)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);
            //System.Configuration.AppSettingsReader settingsReader = new     AppSettingsReader();
            

            if (useHasing)
            {
                var hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes(Key));
                hashmd5.Clear();
            }
            else
            {
                keyArray = Encoding.UTF8.GetBytes(Key);
            }

            var tDes = new TripleDESCryptoServiceProvider
                           {Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};

            ICryptoTransform cTransform = tDes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tDes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        public static string Decrypt(string cypherString, bool useHasing = true)
        {
            byte[] keyArray;
            byte[] toDecryptArray = Convert.FromBase64String(cypherString);
            //byte[] toEncryptArray = Convert.FromBase64String(cypherString);
            //System.Configuration.AppSettingsReader settingReader = new     AppSettingsReader();

            if (useHasing)
            {
                var hashmd = new MD5CryptoServiceProvider();
                keyArray = hashmd.ComputeHash(Encoding.UTF8.GetBytes(Key));
                hashmd.Clear();
            }
            else
            {
                keyArray = Encoding.UTF8.GetBytes(Key);
            }

            var tDes = new TripleDESCryptoServiceProvider
                           {Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};

            ICryptoTransform cTransform = tDes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);

            tDes.Clear();
            return Encoding.UTF8.GetString(resultArray, 0, resultArray.Length);
        }
    }
}
